package net.chrone.query.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

/**
 * @package net.chrone.tpsdk.util
 * @ClassName DingTalkUtil
 * @Description 发送钉钉消息的util类
 * @Author GengQianLong
 * @Date 2018/6/1 12:36
 **/

public class DingTalkUtil {

    static  Logger logger =LoggerFactory.getLogger(DingTalkUtil.class);

    static String ipaddress = null;
    static String apppath = DingTalkUtil.class.getResource("").toString();

    static{
        try{
            Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();
            while (allNetInterfaces.hasMoreElements()){
                NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
                Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
                while (addresses.hasMoreElements()){
                    InetAddress ip = (InetAddress) addresses.nextElement();
                    if (ip != null
                            && ip instanceof Inet4Address
                            && !ip.isLoopbackAddress() //loopback地址即本机地址，IPv4的loopback范围是127.0.0.0 ~ 127.255.255.255
                            && ip.getHostAddress().indexOf(":")==-1){
                        logger.info("本机的IP = " + ip.getHostAddress());
                        ipaddress = ip.getHostAddress();
                    }
                }
            }
        }catch(Exception e){
            logger.error("初始化获取IP地址失败",e);
        }
    }


    /**
     * 通过钉钉发送钉钉消息通知
     * @param msg 消息内容
     * @return
     */
    public static  void sendDingMsg(String msg){

        sendDingMsg(PropertiesUtil.getProperty("dingding.notify.fmkf"),msg);

    }



    /**
     * 通过钉钉发送钉钉消息通知
     * @param dingUrl 机器人地址
     * @param msg 消息内容
     * @return
     */
    public static  void sendDingMsg(String dingUrl,String msg){

        try {
            logger.info("发送钉钉消息："+msg);
            msg=  "当前服务器IP："+ipaddress+"当前项目路径："+apppath+"，消息："+ msg;
            String[] a =new String[]{"Content-Type","application/json; charset=utf-8"};
            List<String[]> strings = new ArrayList<String[]>();
            strings.add(a);
            HttpResponse httpResponse = HttpClientHelper.doHttp(dingUrl,"post",strings,"utf-8", "{ \"msgtype\": \"text\", \"text\": {\"content\": \""+msg+"\"}}", "6000");
            logger.info(httpResponse.getRspStr());
        } catch (Exception e2) {
            logger.error("发送钉消息失败");
        }

    }



    public static void main(String[] args)   {
        System.out.println();
    }
}
